package com.xcity.util;

import java.util.List;
import java.util.Random;

public class RandomUtils {
	public static Random RND = new Random();
	
	public static int getRandomNum(int min, int max){
		if(max > min){
			int rand = RND.nextInt(max - min + 1);
			return rand + min;
		}else if(max == min){
			return min;
		}
		return 0;
	}
	
	/**
	 * weights0[weights0.length - 1]为全体权重总和
	 * @param weights0
	 * @return 权重索引 -1为错误
	 */
	public static int getRandomWeightIndex(int[] weights0){
		int ret = -1;
		if(weights0.length <= 0){
			return -1;
		}
		int rand = getRandomNum(0, weights0[weights0.length - 1] - 1);
		for(int i = 0; i < weights0.length; i++){
			if(rand < weights0[i]){
				ret = i;
				break;	
			}
		}
		return ret;
	}
	
	/**
	 * 把独立权重数组转成累计权重
	 * 
	 * @param weightArray[length - 1] 自己的权重 -> 全体权重
	 * @return
	 */
	public static int transRandomWeightIndex(int[] weightArray){
		int ret = -1;
		int total = 0;
		for(int i = 0; i < weightArray.length; i++){
			total += weightArray[i];
			weightArray[i] = total;
		}
		ret = getRandomWeightIndex(weightArray);
		return ret;
	}
}
